package com.liwenfeng.bigevent.controller;

import com.liwenfeng.bigevent.pojo.LoginOrRegisterDTO;
import com.liwenfeng.bigevent.pojo.Result;
import com.liwenfeng.bigevent.pojo.User;
import com.liwenfeng.bigevent.service.UserService;
import com.liwenfeng.bigevent.utils.JwtUtil;
import com.liwenfeng.bigevent.utils.Md5Util;
import com.liwenfeng.bigevent.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@RequestBody @Validated LoginOrRegisterDTO data) {
        User byName = userService.getByName(data.getUsername());
        if (byName != null)
            return Result.error("用户名已存在");
        userService.insertUser(data.getUsername(), data.getPassword());
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginOrRegisterDTO data) {
        User byName = userService.getByName(data.getUsername());
        if (byName == null)
            return Result.error("用户名不存在！");
        if (!(byName.getPassword().equals(Md5Util.getMD5String(data.getPassword()))))
            return Result.error("密码错误！");
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", byName.getId());
        claims.put("username", byName.getUsername());
        String token = JwtUtil.getToken(claims);
        stringRedisTemplate.opsForValue().set("token", token, Duration.ofHours(12));
        return Result.success(token);
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
//        Map<String, Object> claims = JwtUtil.parseToken(token);
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User byName = userService.getByName(username);
        return Result.success(byName);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User byName = userService.getByName(username);
        if (!StringUtils.hasLength(params.get("oldPwd")) || !StringUtils.hasLength(params.get("newPwd")) || !StringUtils.hasLength(params.get("rePwd")))
            return Result.error("缺少参数！");
        if (!(params.get("newPwd").equals(params.get("rePwd"))))
            return Result.error("两次填写的新密码不一样！");
        if (!(byName.getPassword().equals(Md5Util.getMD5String(params.get("oldPwd")))))
            return Result.error("原密码不正确！");

        userService.updatePwd(Md5Util.getMD5String(params.get("newPwd")), byName.getId());
        stringRedisTemplate.opsForValue().getOperations().delete("token");
        return Result.success();
    }
}
